package com.getpebble.android.framework.receiver;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.Telephony.Sms;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.PblAndroidAppModel;
import com.getpebble.android.common.model.PblAndroidAppModel.Record;
import com.getpebble.android.framework.notification.PblNotificationProcessor;
import com.getpebble.android.framework.notification.PblNotificationProcessor.InvokeActionResult;
import com.getpebble.android.framework.notification.gmail.GmailCheckerService.ActionCallback;
import com.getpebble.android.notifications.model.PblNotification;
import com.getpebble.android.notifications.model.PblNotification.LegacyNotification;
import com.getpebble.android.notifications.model.PblNotification.Source;
import com.getpebble.android.notifications.util.CoreNotifications;
import com.google.common.base.Strings;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.sun.mail.imap.protocol.ListInfo;
import com.sun.mail.smtp.SMTPMessage;

public class SMSReceiver extends BroadcastReceiver {
    private static final String TAG = SMSReceiver.class.getSimpleName();

    public static class SmsNotification extends LegacyNotification {
        public String phoneNumber;
    }

    public void onReceive(Context context, Intent intent) {
        if (context == null) {
            Trace.error(TAG, "Context was null -- not processing SMS notification.");
            return;
        }
        PblPreferences preferences = new PblPreferences(context);
        if (preferences == null || !preferences.getBooleanData(PrefKey.SMS_NOTIFICATIONS, true)) {
            Trace.debug(TAG, "SMS receiver is disabled -- not processing SMS notification.");
            return;
        }
        CoreNotifications.disableNotificationsForSMSClients(context.getApplicationContext());
        CoreNotifications.updateAllowedStateForSMSApps(context.getApplicationContext());
        if (handledByHangouts(context)) {
            Trace.debug(TAG, "Hangouts is SMS receiver, so this is a duplicate message -- not processing SMS notification.");
            return;
        }
        Bundle bundle = intent.getExtras();
        if (bundle == null) {
            Trace.error(TAG, "Bundle was null -- not processing SMS notification.");
            return;
        }
        Trace.debug(TAG, "Processing SMS Notification...");
        Object[] bundlePDUs = (Object[]) bundle.get("pdus");
        SmsMessage[] smsMessages = new SmsMessage[bundlePDUs.length];
        for (int i = 0; i < smsMessages.length; i++) {
            smsMessages[i] = SmsMessage.createFromPdu((byte[]) bundlePDUs[i]);
            if (smsMessages[i] != null) {
                String phoneNumber = smsMessages[i].getOriginatingAddress();
                sendNotificationToWatch(getContactName(context, phoneNumber), Strings.isNullOrEmpty(smsMessages[i].getMessageBody()) ? "" : smsMessages[i].getMessageBody().toString(), phoneNumber);
            }
        }
    }

    private boolean handledByHangouts(Context context) {
        boolean isHangoutsDefault = false;
        if (VERSION.SDK_INT >= 19) {
            isHangoutsDefault = "com.google.android.talk".equals(Sms.getDefaultSmsPackage(context));
        }
        boolean areHangoutsNotificationsEnabled = false;
        Record record = PblAndroidAppModel.getAppRecord("com.google.android.talk", context.getContentResolver());
        if (record != null) {
            areHangoutsNotificationsEnabled = record.chosen;
        }
        return isHangoutsDefault && areHangoutsNotificationsEnabled;
    }

    public static String formatPhoneNumber(String phoneNumber) {
        String result = phoneNumber;
        if (Strings.isNullOrEmpty(phoneNumber)) {
            return "";
        }
        try {
            PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
            result = phoneNumberUtil.format(phoneNumberUtil.parse(phoneNumber, "US"), PhoneNumberFormat.NATIONAL);
        } catch (NumberParseException e) {
            Trace.debug(TAG, "Failed to parse phone number");
        }
        return result;
    }

    protected String getContactName(Context context, String phoneNumber) {
        String contactName = formatPhoneNumber(phoneNumber);
        if (context == null) {
            Trace.error(TAG, "Failed to get contact information -- context was null!");
            return contactName;
        }
        Cursor cursor = null;
        try {
            Uri lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
            cursor = context.getContentResolver().query(lookupUri, new String[]{"display_name"}, null, null, null);
            if (cursor != null && cursor.moveToNext()) {
                contactName = cursor.getString(cursor.getColumnIndexOrThrow("display_name"));
            }
            if (cursor != null) {
                cursor.close();
            }
        } catch (Exception e) {
            Trace.error(TAG, "Failed to retrieve contact info", e);
            if (cursor != null) {
                cursor.close();
            }
        } catch (Throwable th) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return contactName;
    }

    private void sendNotificationToWatch(String sender, String body, String phoneNumber) {
        LegacyNotification content = new SmsNotification();
        content.title = sender;
        content.body = body;
        content.phoneNumber = phoneNumber;
        PblNotificationProcessor.processNotification(PblNotification.from(content, Source.SMS));
    }

    public static void sendSmsReply(String message, String phoneNumber, final ActionCallback callback) {
        SmsManager smsManager = SmsManager.getDefault();
        try {
            PendingIntent sentPendingIntent = PendingIntent.getBroadcast(PebbleApplication.getAppContext(), 0, new Intent("sms_sent_result"), 134217728);
            PebbleApplication.getAppContext().registerReceiver(new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    Trace.debug(SMSReceiver.TAG, "SMS sent callback: onReceive() resultCode = " + getResultCode());
                    context.unregisterReceiver(this);
                    switch (getResultCode()) {
                        case SMTPMessage.NOTIFY_NEVER /*-1*/:
                            callback.result(InvokeActionResult.REPLIED);
                            return;
                        case SMTPMessage.RETURN_FULL /*1*/:
                        case SMTPMessage.RETURN_HDRS /*2*/:
                        case ListInfo.INDETERMINATE /*3*/:
                        case SMTPMessage.NOTIFY_DELAY /*4*/:
                            callback.result(InvokeActionResult.FAILED);
                            return;
                        default:
                            return;
                    }
                }
            }, new IntentFilter("sms_sent_result"));
            smsManager.sendTextMessage(phoneNumber, null, message, sentPendingIntent, null);
            if (VERSION.SDK_INT < 19) {
                try {
                    ContentValues values = new ContentValues();
                    values.put("address", phoneNumber);
                    values.put("body", message);
                    PebbleApplication.getAppContext().getContentResolver().insert(Uri.parse("content://sms/sent"), values);
                } catch (Exception e) {
                    Trace.info(TAG, "Error writing sent message to ContentProvider", e);
                }
            }
        } catch (Exception e2) {
            Trace.error(TAG, "Failed to send SMS message reply.", e2);
            callback.result(InvokeActionResult.FAILED);
        }
    }
}
